package com.howtoplay.Handler.Handshake;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.ObjectUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;

public class WebSocketHandShake implements HandshakeInterceptor {
    private static final Logger log = LoggerFactory.getLogger(WebSocketHandShake.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes)
            throws Exception {
        String collector = ((ServletServerHttpRequest) request).getServletRequest().getParameter("collector");
        if(ObjectUtils.isEmpty(collector)){
            collector = request.getHeaders().get("collector").toString();
        }
        if (collector.equals("null") || collector.length() < 1) {
            return false;
        } else {
            attributes.put("collector", collector);
            return true;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {

    }
}
